/*
 * @Author: your name
 * @Date: 2021-03-30 10:18:07
 * @LastEditTime: 2021-04-10 23:49:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \element实战\element_ui\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'


Vue.use(VueRouter)


//使用路由守卫需要把export default 和挂载Vue 分离

const router = new VueRouter({
  //重定向
  routes: [{
    path: '/',
    redirect: '/login'
  }, {
    path: '/login',
    component: Login
  }, {
    path: '/home',
    component: Home,
    redirect: '/welcome', //首页路由重定向的效果
    children: [{
      path: '/welcome',
      component: Welcome
    }, {

      path: '/users',
      component: Users
    }]
  }] //路由规则
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to将要访问的路径
  //from 代表从哪个路径跳转而来的
  //next 是一个函数 表示放行
  //next() 是一个函数 ，表示放行
  //           next() 放行      next('./login') 强制跳转
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  //获取token
  if (!tokenStr) return next('/login')
  next()
})

export default router